/**
 * 项目名：admin
 * 包名：com.xuebang.admin.controller
 * 文件名：ArticleController.java
 * 版本信息：@version 1.0
 * 日期：2014-1-17-上午11:01:05
 */
package com.xuebang.admin.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.xuebang.admin.dao.Pagination;
import com.xuebang.admin.entity.MenuColumn;
import com.xuebang.admin.entity.NewsContents;
import com.xuebang.admin.entity.NewsTitle;
import com.xuebang.admin.entity.OperatorRules;
import com.xuebang.admin.service.ArticleService;
import com.xuebang.admin.service.ColumnService;
import com.xuebang.admin.util.JsonUtil;
import com.xuebang.admin.web.Result;

/**
 * 项目名称：admin
 * 类名称：ArticleController
 * 类描述：
 * 创建人：xuyang
 * 创建时间：2014-1-17 上午11:01:05
 * 修改人：xuyang
 * 修改时间：2014-1-17 上午11:01:05
 * 修改备注：防止表单二次提交本次没有考虑！
 *   
 * @version 
 */
@Controller
@RequestMapping("/article")
public class ArticleController extends BaseController{
	
	/** KindEditor 分页符 */
	private String strPageBreak = "<hr style=\"page-break-after:always;\" class=\"ke-pagebreak\" />";

	/** 操作页面的下拉框  */
	private StringBuilder downSelectCol = new StringBuilder();
	private Integer choiceCol = null;

	/** 页码 */
	Integer intPageNo = 1;
	/** 页面新闻条数  */
	Integer intPageLimit = 8;
	
	/** 文章业务逻辑类 */
	@Inject
	private ArticleService articleService;
	
	/** 栏目操作类 */
	@Inject
	private ColumnService columnService;
	
//	/**
//	 * 判断浏览器类型
//	 */
//	@ModelAttribute
//	public void voteBrowser (@RequestParam("browserType") String browserType){
//		if("IE".equals(browserType)){
//			strPageBreak = strPageBreak_IE;
//		} else {
//			strPageBreak = strPageBreak_nav;
//		}
//	}

	/**
	 * 展示所有未被删除的文章
	 */
	@RequestMapping(value="/showArticles",method=RequestMethod.GET)
	public String showArticles(){

		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

//		Pagination<NewsTitle> lstNewsTitle =  articleService.getNewsInfo(intPageLimit);
//		model.addAttribute("lstNewsTitle",lstNewsTitle);
//		model.addAttribute("pageSum", lstNewsTitle.totalPages());

		return "redirect:/article/showArticles/0";
	}
	
	/**
	 * 展示所有文章
	 */
	@RequestMapping(value="/showArticles/{red}",method=RequestMethod.GET)
	public String showArticles(Model model,@PathVariable("red") String red){
		

		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...
		int intRed = 0;
		try{
			intRed = Integer.parseInt(red);
		}catch(Exception e){
			e.printStackTrace();
		}
		Pagination<NewsTitle> lstNewsTitle = null;
		if(intRed != 1){
			lstNewsTitle =  articleService.getNewsInfo(intPageLimit);
		} else {
			lstNewsTitle =  articleService.getNewsInfo(intPageLimit,1);
		}
		model.addAttribute("lstNewsTitle",lstNewsTitle);
		model.addAttribute("pageSum", lstNewsTitle.totalPages());
		model.addAttribute("red", red);

		return "/article/showArticles";
	}
	
	/**
	 * 跳转到文章操作页面
	 */
	@RequestMapping(value="/operate",method=RequestMethod.GET)
	public String operate(Model model,HttpServletRequest request){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		
		// 看session中是否存在newsTitle
		Object objErrorMessage = request.getSession().getAttribute("returnMessage");

		if(objErrorMessage!=null){
			StringBuilder sbReturnMessage = (StringBuilder)objErrorMessage;
			if(sbReturnMessage.length()!=0){
				model.addAttribute("returnMessage",sbReturnMessage);
			}
		} else {
			model.addAttribute("returnMessage","");
		}
		
		// 清零
		downSelectCol.setLength(0);
		//20140213 权限处理  add by xy start...
		// 取得所有的栏目
		// 所有的栏目
		List<MenuColumn> lstParentCol = columnService.loadFstColumns(true);
		if(lstParentCol!=null&&lstParentCol.size()!=0){
			for(MenuColumn menuCols: lstParentCol){
				initColumnItem(0,menuCols);
			}
		}
		
		model.addAttribute("downSelectCol", downSelectCol);
		
		// 清空 session
		request.getSession().removeAttribute("returnMessage");
		
		//sidebar 选择菜单
		model.addAttribute("menu1",2);
		model.addAttribute("menu2",1);
		model.addAttribute("menu3",1);
		
		return "/article/operate";
	}
	
	/**
	 * 跳转到添加文章页面
	 * 
	 */
	@RequestMapping(value="/add",method=RequestMethod.GET)
	public String add(NewsTitle newsTitle,Model model,HttpServletRequest request){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		// 看session中是否存在newsTitle
		Object objNewsTitle = request.getSession().getAttribute("newsTitle");
		Object objErrorMessage = request.getSession().getAttribute("returnMessage");
		
		if(objErrorMessage!=null){
			StringBuilder sbReturnMessage = (StringBuilder)objErrorMessage;
			if(sbReturnMessage.length()!=0){
				model.addAttribute("returnMessage",sbReturnMessage);
			}
		} else {
			model.addAttribute("returnMessage","");
		}
		if(objNewsTitle!=null){
			NewsTitle oldNewsTitle = (NewsTitle)objNewsTitle;
			// 下面这句话不好使，不知道为啥？！
			//model.addAttribute("newsTitle",oldNewsTitle);
			try{
				BeanUtils.copyProperties(oldNewsTitle, newsTitle);
			} catch(Exception e){
				e.printStackTrace();
			}
		} else {
			// 默认无缩略图
			newsTitle.setIspic(0);
		}
		
		// 设置默认时间
		if(newsTitle.getPosttime()==null){
			newsTitle.setPosttime(new Date());
		}
		
		model.addAttribute("newsTitle",newsTitle);

		//清除
		request.getSession().removeAttribute("returnMessage");
		request.getSession().removeAttribute("newsTitle");
		model.addAttribute("menu1",1);
		model.addAttribute("menu2",2);
		model.addAttribute("menu3",1);
		
		// 日期 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strCdate = "";
		if(newsTitle.getPosttime()==null){
			strCdate = sdf.format(new Date());
		} else {
			try{
				strCdate = sdf.format(newsTitle.getPosttime());
			} catch(Exception e){
				e.printStackTrace();
				strCdate = sdf.format(new Date());
			}
		}
		model.addAttribute("strCdate",strCdate);

		return "/article/add";
	}

	/**
	 * 增加文章
	 */
	@RequestMapping(value="/toAdd",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public String toAdd(@Valid NewsTitle newsTitle,Model model,HttpServletRequest request){

		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...
		
		//错误信息
		StringBuilder sbReturnMessage = new StringBuilder();
		System.out.println(newsTitle.getPicFile());
		// 上传缩略图
		if(newsTitle.getIspic()==1){
			if(newsTitle.getPicFile().getSize()>0){
				String strPath = uploadPic(newsTitle.getPicFile(),request);
				if(strPath==null) {
					newsTitle.setIspic(0);
				} else {
					newsTitle.setIspic(1);
					newsTitle.setPicurl(strPath);
				}
			} else if(newsTitle.getPicFile().getSize()<=0 && newsTitle.getPicurl()!=null){
				String strPath = newsTitle.getPicurl();
				newsTitle.setIspic(1);
				newsTitle.setPicurl(strPath);
			} else {
				newsTitle.setIspic(0);
			}
		} else {
			newsTitle.setIspic(0);
		}

		//验证
		if(newsValidate(newsTitle,sbReturnMessage)){

			// 初始化未输入的项
			initDoNotInputItem(newsTitle);

			// 内容处理
			List<NewsContents> lstContents =  this.divideContents(newsTitle);
			// 设置页数
			if(lstContents.size()>1){
				newsTitle.setPages(lstContents.size());
			}

			try{
				if(articleService.addNews(newsTitle,lstContents)){
					sbReturnMessage.append("增加成功");
					request.getSession().setAttribute("returnMessage",sbReturnMessage);
					//System.out.println("增加成功。。。。。");
					// 开始增加
					return "redirect:/article/operate";
				}
			} catch(Exception e){
				sbReturnMessage.append("增加失败");
				e.printStackTrace();
			}
		}

		// 将表单信息放入session中待取
		request.getSession().setAttribute("newsTitle", newsTitle);
		request.getSession().setAttribute("returnMessage",sbReturnMessage);

		return "redirect:/article/add";
	}
	
	/**
	 * 跳转到修改文章页面
	 */
	@RequestMapping(value="/update/{id}",method=RequestMethod.GET)
	public String update(@PathVariable Integer id,Model model,HttpServletRequest request){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...
		// 看session中是否存在newsTitle
		Object objErrorMessage = request.getSession().getAttribute("returnMessage");
		if(objErrorMessage!=null){
			StringBuilder sbReturnMessage = (StringBuilder)objErrorMessage;
			if(sbReturnMessage.length()!=0){
				model.addAttribute("returnMessage",sbReturnMessage);
			}
		} else {
			model.addAttribute("returnMessage","");
		}
		// 标题
		NewsTitle newsTitle = articleService.findNews(id);
		// 新闻内容
		List<NewsContents> lstNewsContent = articleService.findContentByTid(id);
		// 数据库中存在2中情况，1是分页， 2是错误的存在
		if(newsTitle.getPages()!=null){
			if(newsTitle.getPages().intValue()==1){
				// 如果是错误情况，则取最新的为真实内容
				newsTitle.setNewsContents(lstNewsContent.get(lstNewsContent.size()-1));
			} else {
				//CKEditor
				int intHasPage = 0;
				// 如果是分页的，则重组内容
				StringBuilder sbContent = new StringBuilder();
				for(NewsContents newsContents : lstNewsContent) {
					if(newsContents.getContents()!=null
							&&!"".equals(newsContents.getContents().trim())){
						if(intHasPage++ >0 ){
							// 分隔符
							sbContent.append(strPageBreak);
						}
						sbContent.append(newsContents.getContents());
					}
				}
//				NewsContents newsContent = lstNewsContent.get(lstNewsContent.size()-1);
//				newsContent.setContents(sbContent.toString());
				NewsContents nc = new NewsContents();
				nc.setContents(sbContent.toString());
				newsTitle.setNewsContents(nc);
			}
		}
		
		model.addAttribute("newsTitle",newsTitle);
		
		// 清空
		request.getSession().removeAttribute("returnMessage");
		
		model.addAttribute("menu1",1);
		model.addAttribute("menu2",1);
		model.addAttribute("menu3",1);
		
		// 日期 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String strCdate = "";
		if(newsTitle.getPosttime()==null){
			strCdate = sdf.format(new Date());
		} else {
			try{
				strCdate = sdf.format(newsTitle.getPosttime());
			} catch(Exception e){
				e.printStackTrace();
				strCdate = sdf.format(new Date());
			}
		}
		model.addAttribute("strCdate",strCdate);

		return "/article/update";
	}
	
	/**
	 * 修改文章
	 */
	@RequestMapping(value="/toUpdate/{id}",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public String toUpdate(@PathVariable Integer id,@ModelAttribute("newsTitle") NewsTitle newsTitle,
			Model model,HttpServletRequest request){

		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...
		
		//initPages
		if(newsTitle.getPages()==null){
			newsTitle.setPages(1);
		}
		
		// 上传缩略图
		if(newsTitle.getIspic()==1){
			if(newsTitle.getPicFile().getSize()>0){
				deleteFile(newsTitle.getPicurl(),request);
				String strPath = uploadPic(newsTitle.getPicFile(),request);
				if(strPath==null) {
					newsTitle.setIspic(0);
				} else {
					newsTitle.setIspic(1);
					newsTitle.setPicurl(strPath);
				}
			} else if(newsTitle.getPicFile().getSize()<=0 && newsTitle.getPicurl()!=null){
				String strPath = newsTitle.getPicurl();
				newsTitle.setIspic(1);
				newsTitle.setPicurl(strPath);
			} else {
				newsTitle.setIspic(0);
			}
		} else {
			newsTitle.setIspic(0);
		}

		//错误信息
		StringBuilder sbReturnMessage = new StringBuilder();
		boolean blnCheckTitle = compareTitle(id,newsTitle.getTitle());
		//验证
		if(newsValidate(newsTitle,sbReturnMessage,blnCheckTitle)){
			
			//NewsContents newsContent = newsTitle.getNewsContents();
			List<NewsContents> lstNewsContent = this.divideContents(newsTitle);

			try{
				articleService.updateNews(newsTitle,lstNewsContent);
				sbReturnMessage.append("修改成功");
				request.getSession().setAttribute("returnMessage", sbReturnMessage);
				// 修改
				return "redirect:/article/operate";
			} catch(Exception e){
				sbReturnMessage.append("修改失败");
				e.printStackTrace();
			}
		}

		request.getSession().setAttribute("returnMessage", sbReturnMessage);
		return "redirect:/article/update/" + id ;
	}
    /**
     * 删除单个文件
     * @param   sPath    被删除文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public void deleteFile(String sPath,HttpServletRequest request) {
    	String basePath = request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\", "/");
    	
        File file = new File(basePath.substring(0, basePath.length()-7)+sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            System.out.println(sPath+"图片删除成功");
        }
    }
	/**
	 * 放入回收站
	 */
	@RequestMapping(value="/toRecycleBin",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String toRecycleBin(@RequestParam String operatorIds){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		try {
			if(operatorIds==null || "".equals(operatorIds.trim())){
				return JsonUtil.dump(Result.error("文章ID不能为空"));
			}
			String[] strArticleIds = operatorIds.split(",");
			if(strArticleIds ==null || strArticleIds.length==0){
				return JsonUtil.dump(Result.error("文章ID不能为空"));
			}
			articleService.putIntoRecycleBin(strArticleIds);
			return JsonUtil.dump(Result.success("放入回收站成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	/**
	 * 还原
	 */
	@RequestMapping(value="/restore",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String restore(@RequestParam String operatorIds){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		try {
			if(operatorIds==null || "".equals(operatorIds.trim())){
				return JsonUtil.dump(Result.error("文章ID不能为空"));
			}
			String[] strArticleIds = operatorIds.split(",");
			if(strArticleIds ==null || strArticleIds.length==0){
				return JsonUtil.dump(Result.error("文章ID不能为空"));
			}
			articleService.restore(strArticleIds);
			return JsonUtil.dump(Result.success("文章还原成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	/**
	 * 删除文章
	 * 
	 */
	@RequestMapping(value="/delArticles",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String delArticles(String operatorIds,HttpServletRequest request){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		try {
			if(operatorIds==null || "".equals(operatorIds.trim())){
				return JsonUtil.dump(Result.error("文章ID不能为空"));
			}
			String[] strArticleIds = operatorIds.split(",");
			if(strArticleIds ==null || strArticleIds.length==0){
				return JsonUtil.dump(Result.error("文章ID不能为空"));
			}
			String basePath = request.getSession().getServletContext().getRealPath("/").replaceAll("\\\\", "/");
			articleService.delArticles(strArticleIds,basePath);
			return JsonUtil.dump(Result.success("删除成功!"));
		} catch (Exception e) {
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	/**
	 * 清空回收站
	 */
	@RequestMapping(value="/clearUp",method = RequestMethod.POST,produces = "text/plain;charset=UTF-8")
	public @ResponseBody String clearUp(){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...
		try{
			articleService.clearUp();
			return JsonUtil.dump(Result.success("清空成功!"));
		} catch(Exception e){
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	/**
	 * 查看回收站
	 */
	@RequestMapping(value="/recycleBin")
	public  String viewRecycleBin(Model model){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		// 清零
		downSelectCol.setLength(0);
		//20140213 权限处理  add by xy start...
		// 取得所有的栏目
		// 所有的栏目
		List<MenuColumn> lstParentCol = columnService.loadFstColumns(true);
		if(lstParentCol!=null&&lstParentCol.size()!=0){
			for(MenuColumn menuCols: lstParentCol){
				initColumnItem(0,menuCols);
			}
		}
		model.addAttribute("downSelectCol",downSelectCol);

		model.addAttribute("menu1",1);
		model.addAttribute("menu2",1);
		model.addAttribute("menu3",2);

		return "/article/recycleBin";
	}
	
	/**
	 * 搜索
	 */
	@RequestMapping(value="/search",method = RequestMethod.GET,produces="text/plain;charset=UTF-8")
	public String search(String searchText,String pageNo){

		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...
		return "redirect:/article/search/0?searchText=" + searchText + "&pageNo="+pageNo;
	}

	/**
	 * 搜索
	 */
	@RequestMapping(value="/search/{red}",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
	public String search(@PathVariable("red") Integer red,String searchText,String pageNo,Model model){
		
		System.out.println("searchText1="+searchText);
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		Pagination<NewsTitle> lstNewsTitle = null;
		if(searchText== null || "".equals(searchText.trim())){
			if(red!=1){
				lstNewsTitle = articleService.getNewsInfo(intPageLimit);
			}else{
				lstNewsTitle = articleService.getNewsInfo(intPageLimit,1);
			}
		} else {
			try{
				intPageNo = Integer.parseInt(pageNo);
			} catch(Exception e){
				e.printStackTrace();
			}
			if(red!=1) {
				lstNewsTitle = articleService.search(searchText.trim(),intPageNo,intPageLimit);
			} else {
				lstNewsTitle = articleService.search(searchText.trim(),red,intPageNo,intPageLimit);
			}
		}

		model.addAttribute("lstNewsTitle",lstNewsTitle);
		model.addAttribute("pageSum", lstNewsTitle.totalPages());
//		System.out.println("pageSum:" + lstNewsTitle.totalPages());
//		System.out.println("search.......end.....");
		return "/article/showArticles";
	}
	
	/**
	 * 过滤新闻
	 * 
	 * @param searchText 搜索项
	 * @param startDate 开始日期
	 * @param endDate 截止日期
	 * @param choiceCol 选中栏目项
	 * @param pageNo 页码
	 */
	@RequestMapping(value="/filterArticles",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
	public String filterArticles(String searchText,String startDate,
			String endDate,Integer choiceCol,Integer pageNo){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		return "redirect:/article/filterArticles/0?searchText="+searchText+"&startDate="
			+startDate+"&endDate="+endDate+"&choiceCol="+choiceCol+"&pageNo="+pageNo;
	}
	
	/**
	 * 过滤新闻
	 * 
	 * @param searchText 搜索项
	 * @param startDate 开始日期
	 * @param endDate 截止日期
	 * @param choiceCol 选中栏目项
	 * @param pageNo 页码
	 */
	@RequestMapping(value="/filterArticles/{red}",method = RequestMethod.GET,produces = "text/plain;charset=UTF-8")
	public String filterArticles(@PathVariable("red") Integer red,String searchText,String startDate,
			String endDate,Integer choiceCol,Integer pageNo,Model model){

		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		if(pageNo == null || pageNo < 1){
			pageNo = 1;
		}
		// 得到截止日期的下一天
		if(endDate!=null&&!"".equals(endDate.trim())){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Calendar cal = Calendar.getInstance();
			try{
				cal.setTime(sdf.parse(endDate));
			} catch(Exception e){
				cal.setTime(new Date());
				e.printStackTrace();
			}
			cal.add(Calendar.DAY_OF_WEEK, 1);
			endDate = sdf.format(cal.getTime());
		}

//		System.out.println("searchText:" + searchText);
//		System.out.println("pageNo:" + pageNo);
//		System.out.println("choiceCol" + choiceCol);
//		System.out.println("startDate" + startDate);
//		System.out.println("endDate" + endDate);
		
		
		Pagination<NewsTitle> lstNewsTitle=null;
		if(red!=1){
			lstNewsTitle =  articleService.filterArticles(searchText, startDate, endDate, choiceCol,pageNo,intPageLimit);
		} else {
			lstNewsTitle =  articleService.filterArticles(searchText, startDate, endDate, choiceCol,pageNo,intPageLimit,red);
		}
		model.addAttribute("lstNewsTitle", lstNewsTitle);
		model.addAttribute("pageSum", lstNewsTitle.totalPages());
//		System.out.println("+++++++++++++++++++++++++");
//		System.out.println("size:" + lstNewsTitle.getData().size());
//		System.out.println("+++++++++++++++++++++++++");
		return "/article/showArticles";
	}
	
	/**
	 * 置顶操作
	 * 
	 * @param String 
	 * 			iftop 置顶级别
	 * @param String
	 * 			id   新闻ID
	 *  
	 */
	@RequestMapping(value="/makeTop",method=RequestMethod.POST,produces="text/plain;charset=UTF-8")
	public @ResponseBody String makeTop(String iftop,String id){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		try{
			int intIfTop = Integer.parseInt(iftop);
			int intId = Integer.parseInt(id);
			articleService.makeTop(intId,intIfTop);
			return JsonUtil.dump(Result.success("修改成功"));
		}catch(Exception e){
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	/**
	 * 推荐操作
	 * 
	 * @param String 
	 * 			 置顶级别
	 * @param String
	 * 			id   新闻ID
	 *  
	 */
	@RequestMapping(value="/recommend",method=RequestMethod.POST,produces="text/plain;charset=UTF-8")
	public @ResponseBody String recomend(String recommendValue ,String id){
		
		//20140213 权限处理  add by xy start...
		if(!this.hasPerm(OperatorRules.PERM_ARTICLE)){
			return this.no_perm_page();
		}
		//20140213 权限处理  add by xy start...

		try{
			int intRecommendValue = Integer.parseInt(recommendValue);
			int intId = Integer.parseInt(id);
			articleService.recommend(intId,intRecommendValue);
			return JsonUtil.dump(Result.success("修改成功"));
		}catch(Exception e){
			e.printStackTrace();
			return JsonUtil.dump(Result.error(e.getMessage()));
		}
	}
	
	/**
	 * ckeditor上传图片
	 * 
	 */
	@RequestMapping(value="/ckEditorUploadImg")
	public String ckEditorUploadImg(){

		return "/article/upload_json";
	}
	
	/**
	 * ckeditor上传file
	 * 
	 */
	@RequestMapping(value="/ckEditorUploadFile")
	public String ckEditorUploadFile(){
		
		return "/article/file_manager_json";
	}
	
	/**
	 * 数据验证
	 * 
	 * @param newsTitle
	 * @param StringBuilder sbErrorMessage
	 */
	private boolean newsValidate(NewsTitle newsTitle,StringBuilder sbErrorMessage,boolean checkTitle){

		boolean blnResult = true;
		// 标题不能为空
		String strTitle = newsTitle.getTitle();
		if(strTitle==null||"".equals(strTitle.trim())){
			blnResult = false;
			sbErrorMessage.append("标题不能为空！");
		} 

		if(checkTitle){
			// 标题不能重复
			Integer intCid = newsTitle.getCid();
			Integer intResult = null;
			try{
	
				if(blnResult && intCid != null){
					 intResult =  articleService.findNewsByName(strTitle,intCid);
				} else {
					 if(blnResult){
						 // 栏目为null的情况
						 intResult = articleService.findNewsByName(strTitle);
					 }
				}
			} catch(Exception e){
				// 标题重复（数据库报结果太多异常）
				intResult  = 1;
				e.printStackTrace();
			}
			if(intResult != null){
				if(!blnResult){
					sbErrorMessage.append("/r/n");
				}
				// 这个应该用国际化的！
				sbErrorMessage.append("标题重复！");
				blnResult = false;
			}
		}

		// 内容
		if(newsTitle.getNewsContents()==null||newsTitle.getNewsContents().getContents()==null
				||"".equals(newsTitle.getNewsContents().getContents().trim())){
			if(!blnResult){
				sbErrorMessage.append("/r/n");
			} 
			sbErrorMessage.append("标题不能为空！");	
			blnResult = false;
		}
//		System.out.println("+++++++++++++++++++++++++++");
//		System.out.println("error:" + sbErrorMessage);
//		System.out.println("+++++++++++++++++++++++++++");
		return blnResult;
	}
	
	/**
	 * 数据验证
	 * 
	 * @param newsTitle
	 * @param StringBuilder sbErrorMessage
	 */
	private boolean newsValidate(NewsTitle newsTitle,StringBuilder sbErrorMessage){
		
		return newsValidate(newsTitle,sbErrorMessage,true);
	}
	
	/**
	 * 比较新旧标题是否改变
	 * 
	 * @param id
	 * @param newTitle
	 */
	private boolean compareTitle(Integer id,String newerTitle){
		
		// 返回是否需要检查标题
		boolean blnCheckTitle = false;
		if(newerTitle!=null && !"".equals(newerTitle.trim())){
			NewsTitle newsTitle = articleService.findNews(id);
			// 不一样则需要检查title
			if(!newerTitle.equals(newsTitle.getTitle())){
				blnCheckTitle = true;
			}
		}
		return blnCheckTitle;
	}
	
	/**
	 * 文件上传
	 * 
	 * @param picFile
	 * 	图片文件
	 * @param request
	 * 	请求
	 */
	private String uploadPic(CommonsMultipartFile picFile,HttpServletRequest request){
		
		String strPicPath = null;
		try{
			// 构建文件保存的目录
			SimpleDateFormat dateformat = new SimpleDateFormat("yyyyMMdd");
	        String logoPathDir = "/upload/" + dateformat.format(new Date());
	        // 得到文件保存目录的真实路径
	        String logoRealPathDir = request.getSession().getServletContext()
	                .getRealPath(logoPathDir).replaceAll("\\\\", "/");
	        // 根据真实路径创建目录
	        File logoSaveFile = new File(logoRealPathDir);
	        if (!logoSaveFile.exists())
	            logoSaveFile.mkdirs();

	        // 文件后缀
	        String suffix = picFile.getOriginalFilename().substring(
	        		picFile.getOriginalFilename().lastIndexOf("."));
	        // 文件名=上传文件名+年月日时分秒
	        SimpleDateFormat dat = new SimpleDateFormat("yyyyMMddHHmmss");
	        String strFileName = picFile.getOriginalFilename() + "_" + dat.format(new Date()) + suffix;
			String strRealFileName = logoRealPathDir + "/" + strFileName;
			File file = new File(strRealFileName);
			picFile.transferTo(file);
			//图片加水印logo
			//ImageUtils.pressImage(request.getSession().getServletContext().getRealPath("/images/logo/logo-cn.png").replaceAll("\\\\", "/"), strRealFileName, 0, 0);
			
			strPicPath = request.getContextPath() + logoPathDir + "/" + strFileName;
		}catch(Exception e){
			e.printStackTrace();
		}
		return strPicPath;
	}
	
	/**
	 * 初始化那些未输入的项
	 */
	private void initDoNotInputItem(NewsTitle newsTitle){
		
		// edittime(首次修改时间按照发布时间来)
		newsTitle.setEdittime(newsTitle.getPosttime());
		// new_type(新闻类型)
		newsTitle.setNewType(0);
		// red (不在回收站中)
		newsTitle.setRed(0);
		// 
		newsTitle.setPages(1);
	}
	
	/**
	 * 划分内容
	 * 
	 * @param NewsTitle
	 */
	private List<NewsContents> divideContents(NewsTitle newsTitle){
		
		List<NewsContents> lstNewsContents = new ArrayList<NewsContents>();
		if(newsTitle!=null) {
			NewsContents newsContent = newsTitle.getNewsContents();
			// 栏目
			newsContent.setCid(newsTitle.getCid());
			// 发布时间
			newsContent.setPosttime(newsTitle.getPosttime());
			String[] arrayNewsContent = newsContent.getContents().split(this.strPageBreak);
			for(String strNewsContent: arrayNewsContent){
				if(strNewsContent!=null && !"".equals(strNewsContent)){
					NewsContents newsContentsItem = new NewsContents();
					try{
						BeanUtils.copyProperties(newsContent, newsContentsItem);
						newsContentsItem.setContents(strNewsContent);
						lstNewsContents.add(newsContentsItem);
					} catch(Exception e){
						e.printStackTrace();
					}
				}
			}
		}
		return lstNewsContents;
	}
	
	/**
	 * 找到每个一级栏目的子孙栏目
	 */
	private void initColumnItem(int intNumFloor,MenuColumn menuColumns){

		List<MenuColumn> lstTempMenuColumns = columnService.loadChildColumns(menuColumns.getId(),true);
		int i = intNumFloor;
		// 防止死循环，目前最多只有3级
		if(intNumFloor>=3){
			return;
		}
		downSelectCol.append("<option value=\"");
		downSelectCol.append(menuColumns.getId() + "\"");
		if(choiceCol!=null &&choiceCol.intValue()==menuColumns.getId().intValue()){
			downSelectCol.append("selected=\"selected\"");
		}
		downSelectCol.append(">");
		while(i-- > 0) {
			downSelectCol.append("|--");
		}
		downSelectCol.append(menuColumns.getName());

		downSelectCol.append("</option>");
		if(lstTempMenuColumns != null && lstTempMenuColumns.size() != 0) {
			intNumFloor++;
			for(MenuColumn tempMenuColumn : lstTempMenuColumns){
				initColumnItem(intNumFloor,tempMenuColumn);
			}
		}
	}
}
/************************ 修改履历  ***************
 *   修改人                                       修改时间                                                         修改缘由
 *   xy             2014-1-17             新建
 *
 *
 */

